package yc.web.servlets;

import yc.bean.User;
import yc.utils.EncryptUtils;
import yc.utils.YcConstants;
import yc.web.model.JsonModel;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

@WebServlet("/user.action")
public class UserServlet extends BaseServlet {
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, InvocationTargetException, InstantiationException, IllegalAccessException {
        JsonModel jm = new JsonModel();
        User c=super.parseObjectFromRequest(req, User.class);
        String valcode=req.getParameter("valcode");
        //取出session的验证码
        HttpSession session=req.getSession();
        boolean validate=true ;//控制登录的时候是否需要验证码，当其为true时表示开启，需要验证码登录。
        if (validate){
        String code=(String) session.getAttribute("code");
        if (validate &&!code.equals(valcode)){
            jm.setCode(0);
            jm.setError("验证码错误...");
            super.writeJson(jm,resp);
            return;
        }}
        String newPwd= EncryptUtils.encrytToMD5(EncryptUtils.encrytToMD5(c.getPwd()));
        c.setPwd(newPwd);
        String sql="select * from resuser where username=? and pwd=?";
        List<User>list=db.select(User.class,sql,c.getUsername(),c.getPwd());
        if (list!=null&&list.size()>0){
            //记录用户的登录状态
            session.setAttribute("logincust",list.get(0));
            jm.setCode(1);
            list.get(0).setPwd("别偷看");//将返回数据中的密码设置好，减少风险
            jm.setObj(list.get(0));
            //登录用户的信息记录到session中去
            session.setAttribute(YcConstants.REUSER,list.get(0));
            //访问redis
        }else{
            jm.setCode(0);
            jm.setError("用户名或密码错误");
        }
        super.writeJson(jm,resp);
    }
    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, InvocationTargetException, InstantiationException, IllegalAccessException {
        JsonModel jm = new JsonModel();
        HttpSession session=req.getSession();
        session.removeAttribute("user");
        jm.setCode(1);
        super.writeJson(jm,resp);
    }
    protected void checkLogin(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, InvocationTargetException, InstantiationException, IllegalAccessException {
        JsonModel jm = new JsonModel();
        HttpSession session=req.getSession();
        if (session.getAttribute("user")!=null){
            jm.setCode(1);
           User user=(User) session.getAttribute("user");
           user.setPwd("别偷看");
           jm.setObj(user);
        }else{
            jm.setCode(0);
        }
        writeJson(jm,resp);
    }
}
